/*
 * ImageCache.cpp
 *
 *  Created on: 20/10/2009
 *      Author: marcos
 */

#include "ImageCache.h"

namespace gui {

ImageCache::ImageCache() {
}

ImageCache::~ImageCache() {
	util::LinkedList<std::string>::Iterator it = this->hash.keySet().iterator();
	while (it.hasNext()) {
		this->freeImage(*it.next());
	}
}

SDL_Surface* ImageCache::getImage(std::string filename) {
	if (this->hash.containsKey(filename)){
		SDL_Surface* ret = this->hash.get(filename);
		if (ret != NULL) {
			return ret;
		}
	}
	SDL_Surface* image = this->loadImage(filename);
	this->hash.put(filename, image);
	return image;
}

void ImageCache::freeImage(std::string filename) {
	SDL_Surface* surface = this->hash.remove(filename);
	SDL_FreeSurface(surface);
}

SDL_Surface* ImageCache::loadImage(std::string filename) {
	SDL_Surface* tempImage = NULL;
	SDL_Surface* optimizedImage = NULL;

	tempImage = SDL_LoadBMP(filename.c_str());
	optimizedImage = SDL_DisplayFormat(tempImage);
	SDL_FreeSurface(tempImage);

	SDL_SetColorKey(optimizedImage, SDL_RLEACCEL | SDL_SRCCOLORKEY, SDL_MapRGB(optimizedImage->format,255,0,255));

	return optimizedImage;
};

} // end of namespace
